<template>
  <div style="width: 100%;height: 100%;">
    <div style="width: 100%;height: 100%;" id="locationMap"></div>
    <div style="width: 80px;height: 30px;position: absolute;left: calc(50% - 40px);
    bottom: 20px;z-index: 50;background-color: #00a3af;color: white;
    border-radius: 6px;
    cursor: pointer;
    line-height: 30px;text-align: center" @click="getPic" :class="confirmBtnClass">{{confirmText}}
    </div>
    <transition name="fade">
      <img :src="imageData" v-if="showImage" style="width: 50%;height: 50%;position: absolute;top: 25%;left: 25%;z-index: 200"/>
    </transition>
  </div>
</template>

<script>
  import Bbox from "@turf/bbox";
  import mapboxgl from "mapbox-gl";
  import * as turfMeta from '@turf/meta';
  import * as turfInvariant from '@turf/invariant';

  export default {
    name: "LocationMapImage",
    data() {
      return {
        style: {
          "updatedAt": "2021-01-26T03:13:12.518Z",
          "createdAt": "2019-10-25T07:23:12.578Z",
          "owner": "gykj",
          "zoom": 16.43135858288883,
          "sources": {
            "天地图注记": {
              "tileSize": 256,
              "tiles": ["https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=40da7abcd3265b23d7b867b4eaf479da"],
              "type": "raster"
            },
            "satellite": {
              "tileSize": 256,
              "tiles": ["https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=40da7abcd3265b23d7b867b4eaf479da"],
              "type": "raster"
            }
          },
          "name": "养殖险地图",
          "sprite": "http://gykj123.cn:9035/api/v1/sprites/gykj/r1vbPWb_7/sprite",
          "glyphs": "http://gykj123.cn:9035/api/v1/fonts/gykj/{fontstack}/{range}.pbf",
          "layers": [{
            "layout": {"visibility": "visible"},
            "paint": {"background-color": "rgb(4,7,14)"},
            "type": "background",
            "id": "背景"
          }, {
            "layout": {"visibility": "visible"},
            "source": "satellite",
            "type": "raster",
            "id": "卫星影像"
          }, {"layout": {"visibility": "visible"}, "source": "天地图注记", "type": "raster", "id": "POI注记"}],
          "transition": {},
          "pitch": 0,
          "bearing": 0,
          "center": [114.88185762031094, 34.927337912401015],
          "version": 8,
          "tags": [],
          "type": "normal",
          "scope": "public",
          "style_id": "ryFyQme9r"
        },
        jsonData:null,
        showImage:false,
        imageData:null,
      }
    },
    props: {
      geoJson: {
        type: Object,
        default: function () {
          return null
        }
      },
      featureCollection: {
        type: Object,
        default: function () {
          return null
        }
      },
      confirmText: {
        type: String,
        default: "保存"
      },
      confirmBtnClass: {
        type: String,
        default: ""
      },
    },
    mounted() {
      let map = new mapboxgl.Map({
        container: "locationMap",
        style: this.style,
        maxZoom: 16.99,
        zoom: 14,
        center: [111.929173, 32.67442],
        dragRotate: false,
        pitchWithRotate: false,
        touchZoomRotate: true,
        refreshExpiredTiles: true,
        preserveDrawingBuffer: true
      });
      this.map = map;
      //解决canvas渲染不正确
      map.on("styledata", function () {
        map.resize();
      });
      map.on("load", () => {
        this.translateJson();
        if(this.geoJson){
          this.fitJson();
          this.drawJson();
          this.drawPoint();
        }
        if(this.featureCollection){
          this.drawFeatures();
        }
      });

    },
    watch: {
      geoJson: function (val) {
        this.translateJson();
        if (val) {
          this.fitJson();
          this.drawJson();
          this.drawPoint();
        }
      } ,
      featureCollection: function (val) {
        if (val) {
          this.drawFeatures();
        }
      }
    },
    methods: {
      translateJson(){
        if(this.geoJson){
          let temp =JSON.parse(JSON.stringify(this.geoJson));
          this.jsonData=turfInvariant.getGeom(temp);
        }else {
          this.jsonData=null;
        }
      },
      getPic() {
        let img = this.map.getCanvas().toDataURL();
        this.$emit("createPng", img);
        this.imageData=img;
        this.showImage=true;
        setTimeout(()=>{
          this.showImage=false
        },2000)
      },
      //地图缩放到指定范围
      fitJson() {
        if (this.jsonData) {
          let box = Bbox(this.jsonData);
          this.map.fitBounds(
            [
              [box[0], box[1]],
              [box[2], box[3]],
            ],
            {
              padding: {
                top: 100,
                bottom: 100,
                left: 100,
                right: 100,
              },
            }
          ); //设置地图定位范围
        }
      },
      drawJson() {

        if (this.map.getLayer("maine")) {
          this.map.removeLayer("maine")
        }
        if (this.map.getSource("maine")) {
          this.map.removeSource("maine")
        }
        this.map.addSource("maine", {
          type: "geojson",
          data: {
            type: "Feature",
            geometry: this.jsonData,
          },
        });
        this.map.addLayer({
          id: "maine",
          type: "line",
          source: "maine",
          layout: {},
          paint: {
            "line-color": "#F00",
            "line-width": 3,
          },
        });
      },
      drawFeatures() {
        if (this.map.getLayer("maine1")) {
          this.map.removeLayer("maine1")
        }
        if (this.map.getSource("maine1")) {
          this.map.removeSource("maine1")
        }
        this.map.addSource("maine1", {
          type: "geojson",
          data: this.featureCollection,
        });
        this.map.addLayer({
          id: "maine1",
          type: "line",
          source: "maine1",
          layout: {},
          paint: {
            "line-color": ["get","color"],
            "line-width": 3,
          },
        });
      },
      drawPoint() {
        let coords = turfMeta.coordAll(this.jsonData);


        if (!coords || coords.length === 0) {
          return;
        }
        if (this.map.getLayer("coordText")) {
          this.map.removeLayer("coordText")
        }
        if (this.map.getLayer("coordPoint")) {
          this.map.removeLayer("coordPoint")
        }
        if (this.map.getSource("coordText")) {
          this.map.removeSource("coordText")
        }

        let source = {
          type: "FeatureCollection",
          features: [],
        };
        for (let i = 0; i < coords.length; i++) {
          source.features.push(
            {
              type: "Feature",
              properties: {
                text: coords[i][0].toFixed(6) + "\n" + coords[i][1].toFixed(6),
                bz: "2222"
              },
              geometry: {
                type: "Point",
                coordinates: coords[i]
              }
            }
          )
        }
        this.map.addSource("coordText", {
          type: "geojson",
          data: source,
        });

        this.map.addLayer(
          {
            "id": "coordText",
            "source": "coordText",
            "type": "symbol",
            "minzoom": 1,
            "maxzoom": 18,
            "layout": {
              "text-field": "{text}",
              "text-font": [
                "FZHei-B01S Regular"
              ],
              "text-size": 14,
              "text-line-height": 1,
              "text-anchor": "bottom",
              "text-offset": [
                -1,
                -1
              ],
              "visibility": "visible"
            },
            "paint": {
              "text-opacity": 1,
              "text-color": "#ffffff",
              "text-halo-color": "#991c2e",
              "text-halo-width": 1
            }
          });
        this.map.addLayer(
          {
            "id": "coordPoint",
            "source": "coordText",
            "type": "circle",
            "minzoom": 1,
            "maxzoom": 18,
            "layout": {
              "visibility": "visible"
            },
            "paint": {
              "circle-color": "#991c2e",
            }
          });
      }
    },
  }
</script>
<style>
  @import url("https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css");
</style>
<style scoped>
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity .5s
  }
  .fade-enter,
  .fade-leave-active {
    opacity: 0
  }
  img{
    border: 5px solid white;
    border-radius: 10px;
    box-sizing: border-box;
  }
</style>
